package cn.kimming.system.task;

import cn.kimming.common.pojo.Room;
import cn.kimming.common.pojo.RoomPlan;
import cn.kimming.common.pojo.RoomType;
import cn.kimming.common.util.DateUtil;
import cn.kimming.common.vo.DefaultPriceVO;
import cn.kimming.mapper.RoomMapper;
import cn.kimming.mapper.RoomPlanMapper;
import cn.kimming.mapper.RoomTypeMapper;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;

/**
 * @author 刘铭轩
 * date 2021-06-02
 */

@Configuration
@EnableScheduling
@Slf4j
public class WebSystemTask {

    public WebSystemTask() {
        System.out.println("hah");
    }

    @Autowired
    private RoomTypeMapper roomTypeMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RoomPlanMapper roomPlanMapper;

    /**
     * 定时任务
     * 执行时间: 每天0时0分0秒
     * 执行内容: 为20天内尚未设置预定计划的房型生成默认预定计划
     */
    @Scheduled(cron = "* 0/30 * * * ?")
    public void generateRoomTypeDefaultPrice() {
        log.info("执行定时任务: generateRoomTypeDefaultPrice");
        List<Date> dates = DateUtil.getRecent20Dates();
        List<DefaultPriceVO> vos = roomTypeMapper.listDefaultPrice();
        for (DefaultPriceVO type : vos) {
            Long typeCount = roomMapper.findCountByTypeId(type.getId());
            for (Date date : dates) {
                RoomPlan roomPlan = roomPlanMapper.findByTypeIdAndDate(type.getId(), date);
                boolean isWeekend = DateUtil.isWeekend(date);
                if (roomPlan != null) continue;
                roomPlan = RoomPlan.builder()
                        .roomTypeId(type.getId())
                        .futureDate(date)
                        .discount(1.0D)
                        .price(isWeekend ? type.getWeekendPrice() : type.getWorkdayPrice())
                        .repertory(typeCount.intValue())
                        .build();
                roomPlanMapper.insertSelective(roomPlan);
            }
        }
    }
}
